<!doctype html>



  


<html class="theme-next mist use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>



<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />












  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.0" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="微服务,microservice,Gitlab,配置管理,Cfg4j,Consul,Jenkins,Vault," />








  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.1.0" />






<meta name="description" content="cfg4j是一个开源的为分布式系统设计的轻量的简单易用的配置管理工具，可以与Spring，Guice及其它DI无缝集成，支持JSON，YAML，Java Properties等配置格式，支持Git仓库，Consul，文件及系统环境变量等多种配置存储机制。">
<meta property="og:type" content="article">
<meta property="og:title" content="微服务之配置管理（2）—— Cfg4j">
<meta property="og:url" content="http://chrisrc.me/2017/02/18/configuration-management-on-dcos-cfg4j/index.html">
<meta property="og:site_name" content="山中，山外与俯瞰">
<meta property="og:description" content="cfg4j是一个开源的为分布式系统设计的轻量的简单易用的配置管理工具，可以与Spring，Guice及其它DI无缝集成，支持JSON，YAML，Java Properties等配置格式，支持Git仓库，Consul，文件及系统环境变量等多种配置存储机制。">
<meta property="og:updated_time" content="2017-02-19T08:07:43.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="微服务之配置管理（2）—— Cfg4j">
<meta name="twitter:description" content="cfg4j是一个开源的为分布式系统设计的轻量的简单易用的配置管理工具，可以与Spring，Guice及其它DI无缝集成，支持JSON，YAML，Java Properties等配置格式，支持Git仓库，Consul，文件及系统环境变量等多种配置存储机制。">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Mist',
    sidebar: {"position":"left","display":"post"},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://chrisrc.me/2017/02/18/configuration-management-on-dcos-cfg4j/"/>





  <title> 微服务之配置管理（2）—— Cfg4j | 山中，山外与俯瞰 </title>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  










  
  
    
  

  <div class="container one-collumn sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-meta ">
  

  <div class="custom-logo-site-title">
    <a href="/"  class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <span class="site-title">山中，山外与俯瞰</span>
      <span class="logo-line-after"><i></i></span>
    </a>
  </div>
  <p class="site-subtitle">一次永不停止的探索之旅</p>
</div>

<div class="site-nav-toggle">
  <button>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
  </button>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-dcos">
          <a href="/dcos" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-book"></i> <br />
            
            DC/OS
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="st-search-show-outputs">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <form class="site-search-form">
  <input type="text" id="st-search-input" class="st-search-input st-default-search-input" />
</form>

<script type="text/javascript">
  (function(w,d,t,u,n,s,e){w['SwiftypeObject']=n;w[n]=w[n]||function(){
    (w[n].q=w[n].q||[]).push(arguments);};s=d.createElement(t);
    e=d.getElementsByTagName(t)[0];s.async=1;s.src=u;e.parentNode.insertBefore(s,e);
  })(window,document,'script','//s.swiftypecdn.com/install/v2/st.js','_st');

  _st('install', 'R9GcmhBwxpsAGLNCsquZ','2.0.0');
</script>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">
  <link itemprop="mainEntityOfPage" href="http://chrisrc.me/2017/02/18/configuration-management-on-dcos-cfg4j/">

  <span style="display:none" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <meta itemprop="name" content="chrisrc">
    <meta itemprop="description" content="">
    <meta itemprop="image" content="/images/avatar.gif">
  </span>

  <span style="display:none" itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
    <meta itemprop="name" content="山中，山外与俯瞰">
    <span style="display:none" itemprop="logo" itemscope itemtype="http://schema.org/ImageObject">
      <img style="display:none;" itemprop="url image" alt="山中，山外与俯瞰" src="">
    </span>
  </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                微服务之配置管理（2）—— Cfg4j
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>
              <time title="Post created" itemprop="dateCreated datePublished" datetime="2017-02-18T18:28:18+08:00">
                2017-02-18
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
              <span class="post-meta-divider">|</span>
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/微服务/" itemprop="url" rel="index">
                    <span itemprop="name">微服务</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <a href="/2017/02/18/configuration-management-on-dcos-cfg4j/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count ds-thread-count" data-thread-key="2017/02/18/configuration-management-on-dcos-cfg4j/" itemprop="commentCount"></span>
                </a>
              </span>
            
          

          

          
          

          

          

        </div>
      </header>
    


    <div class="post-body" itemprop="articleBody">

      
      

      
        <p><a href="http://www.cfg4j.org/" target="_blank" rel="external">cfg4j</a>是一个开源的为分布式系统设计的轻量的简单易用的配置管理工具，可以与Spring，Guice及其它DI无缝集成，支持JSON，YAML，Java Properties等配置格式，支持Git仓库，Consul，文件及系统环境变量等多种配置存储机制。</p>
<a id="more"></a>
<p>cfg4j主要包括以下特性：</p>
<ul>
<li><p>配置自动重新加载：每个服务每隔特定时间可以重新加载配置并自动重新配置自身。</p>
</li>
<li><p>多环境支持：适用于用户定义的各种环境，如：测试，预发布，金丝雀部署，各种生产环境等。</p>
</li>
<li><p>本地缓存：在推送缓存或配置库关闭时防止服务中断，并提高获取配置的性能。</p>
</li>
<li><p>回退和合并策略：简化本地开发，同时支持多个配置存储库。</p>
</li>
<li><p>多DI框架支持：支持Spring，Guice等多种DI。</p>
</li>
</ul>
<h3 id="功能示例"><a href="#功能示例" class="headerlink" title="功能示例"></a>功能示例</h3><h4 id="添加依赖"><a href="#添加依赖" class="headerlink" title="添加依赖"></a>添加依赖</h4><figure class="highlight xml"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div></pre></td><td class="code"><pre><div class="line"><span class="tag">&lt;<span class="name">dependencies</span>&gt;</span></div><div class="line">    <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></div><div class="line">        <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.cfg4j<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></div><div class="line">        <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>cfg4j-core<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></div><div class="line">        <span class="tag">&lt;<span class="name">version</span>&gt;</span>4.4.0<span class="tag">&lt;/<span class="name">version</span>&gt;</span></div><div class="line">    <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></div><div class="line">    <span class="comment">&lt;!-- Optional plug-ins --&gt;</span></div><div class="line">    <span class="comment">&lt;!-- Consul integration --&gt;</span></div><div class="line">    <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></div><div class="line">        <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.cfg4j<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></div><div class="line">        <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>cfg4j-consul<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></div><div class="line">        <span class="tag">&lt;<span class="name">version</span>&gt;</span>4.4.0<span class="tag">&lt;/<span class="name">version</span>&gt;</span></div><div class="line">    <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></div><div class="line">    <span class="comment">&lt;!-- Git integration --&gt;</span></div><div class="line">    <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></div><div class="line">        <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.cfg4j<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></div><div class="line">        <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>cfg4j-git<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></div><div class="line">        <span class="tag">&lt;<span class="name">version</span>&gt;</span>4.4.0<span class="tag">&lt;/<span class="name">version</span>&gt;</span></div><div class="line">    <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></div><div class="line"><span class="tag">&lt;/<span class="name">dependencies</span>&gt;</span></div></pre></td></tr></table></figure>
<h4 id="初始化配置服务"><a href="#初始化配置服务" class="headerlink" title="初始化配置服务"></a>初始化配置服务</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div></pre></td><td class="code"><pre><div class="line"></div><div class="line"><span class="meta">@Configuration</span></div><div class="line"><span class="class"><span class="keyword">class</span> <span class="title">Cfg4jBeansConfig</span> </span>&#123;</div><div class="line"></div><div class="line">    <span class="meta">@Value</span>(<span class="string">"$&#123;configuration.endpoint.protocol:http&#125;"</span>)</div><div class="line">    <span class="keyword">private</span> String configurationEndpointProtocol;</div><div class="line"></div><div class="line">    <span class="meta">@Value</span>(<span class="string">"$&#123;configuration.endpoint.hostname:youForgotToSpecifyHost&#125;"</span>)</div><div class="line">    <span class="keyword">private</span> String configurationEndpoint;</div><div class="line"></div><div class="line">    <span class="meta">@Value</span>(<span class="string">"$&#123;configuration.endpoint.port:8500&#125;"</span>)</div><div class="line">    <span class="keyword">private</span> <span class="keyword">int</span> configurationEndpointPort;</div><div class="line"></div><div class="line">    <span class="meta">@Bean</span></div><div class="line">    <span class="function">ConfigurationSource <span class="title">globalConfigurationSource</span><span class="params">()</span> <span class="keyword">throws</span> MalformedURLException </span>&#123;</div><div class="line">        <span class="keyword">return</span> <span class="keyword">new</span> ConsulConfigurationSourceBuilder()</div><div class="line">            .withHost(configurationEndpoint)</div><div class="line">            .withPort(configurationEndpointPort)</div><div class="line">            .build();</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="meta">@Bean</span></div><div class="line">    <span class="function">ConfigurationProvider <span class="title">configurationProvider</span><span class="params">(ConfigurationSource configurationSource,</span></span></div><div class="line">    @Value(<span class="string">"$&#123;configuration.environment&#125;"</span>) String configurationEnvironment) &#123;</div><div class="line">        <span class="keyword">return</span> <span class="keyword">new</span> ConfigurationProviderBuilder()</div><div class="line">            .withConfigurationSource(configurationSource)</div><div class="line">            .withEnvironment(<span class="keyword">new</span> ImmutableEnvironment(<span class="string">"app/"</span> + configurationEnvironment + <span class="string">"/feature"</span>))</div><div class="line">            .withReloadStrategy(<span class="keyword">new</span> PeriodicalReloadStrategy(<span class="number">30</span>, TimeUnit.SECONDS))</div><div class="line">            .build();</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="keyword">public</span> <span class="class"><span class="keyword">interface</span> <span class="title">SearchConfig</span> </span>&#123;</div><div class="line">        <span class="function">String <span class="title">defaultQuery</span><span class="params">()</span></span>;</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="meta">@Bean</span></div><div class="line">    <span class="function">SearchConfig <span class="title">searchConfig</span><span class="params">(ConfigurationProvider configurationProvider)</span> </span>&#123;</div><div class="line">        <span class="keyword">return</span> configurationProvider.bind(<span class="string">"search"</span>, SearchConfig.class);</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>应用通过配置对象注入配置，而不是直接提供配置。这里也有两种方案：</p>
<ul>
<li>直接注入配置（配置变更时不会自动更新）</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line">String defaultQuery = configurationProvider.getProperty(<span class="string">"search.defaultQuery"</span>, String.class);</div><div class="line"></div><div class="line"><span class="keyword">if</span>(queryEmpty()) &#123;</div><div class="line">    <span class="keyword">return</span> defaultQuery;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<ul>
<li>通过接口绑定注入配置（配置变更时会自动更新）</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div></pre></td><td class="code"><pre><div class="line">SearchConfig config = configurationProvider.bind(<span class="string">"search"</span>, SearchConfig.class);</div><div class="line"></div><div class="line"><span class="comment">// in search method</span></div><div class="line"><span class="keyword">if</span>(queryEmpty()) &#123;</div><div class="line">    <span class="keyword">return</span> config.defaultQuery();</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<h4 id="访问配置"><a href="#访问配置" class="headerlink" title="访问配置"></a>访问配置</h4><p>直接获取原始类型的配置：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div></pre></td><td class="code"><pre><div class="line">Boolean property = provider.getProperty(<span class="string">"some.property"</span>, Boolean.class); <span class="comment">// some.property=false</span></div><div class="line"></div><div class="line">Integer property = provider.getProperty(<span class="string">"some.other.property"</span>, Integer.class); <span class="comment">// some.other.property=1234</span></div><div class="line"></div><div class="line"><span class="keyword">float</span>[] floats = provider.getProperty(<span class="string">"my.floatsArray"</span>, <span class="keyword">float</span>[].class); <span class="comment">// my.floatsArray=1.2,99.999,0.15</span></div><div class="line"></div><div class="line">URL url = provider.getProperty(<span class="string">"my.url"</span>, URL.class); <span class="comment">// my.url=http://www.cfg4j.org</span></div></pre></td></tr></table></figure>
<p>直接获取集合类型的配置：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line">List&lt;String&gt; stringList = provider.getProperty(<span class="string">"some.string.list"</span>, <span class="keyword">new</span> GenericType&lt;List&lt;String&gt;&gt;() &#123;&#125;); <span class="comment">// some.string.list=how,are,you</span></div><div class="line"></div><div class="line">Map&lt;String, Integer&gt; pairs = provider.getProperty(<span class="string">"some.map"</span>, <span class="keyword">new</span> GenericType&lt;Map&lt;String, Integer&gt;&gt;() &#123;&#125;); <span class="comment">// some.map=a=1,b=33,c=-10</span></div></pre></td></tr></table></figure>
<p>直接获取配置对象：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div></pre></td><td class="code"><pre><div class="line"><span class="comment">// Define your configuration interface</span></div><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">interface</span> <span class="title">MyConfiguration</span> </span>&#123;</div><div class="line">    <span class="function">Boolean <span class="title">featureToggle</span><span class="params">()</span></span>;</div><div class="line">    File[] someFiles();</div><div class="line">    <span class="function">Map&lt;String, Integer&gt; <span class="title">prices</span><span class="params">()</span></span>;</div><div class="line">&#125;</div><div class="line"></div><div class="line"><span class="comment">// someFeature.featureToggle=true</span></div><div class="line"><span class="comment">// someFeature.someFiles=/temp/fileA.txt,/temp/fileB.txt</span></div><div class="line"><span class="comment">// someFeature.prices=apple=1,candy=33,car=10</span></div><div class="line">MyConfiguration config = simpleConfigurationProvider.bind(<span class="string">"someFeature"</span>, MyConfiguration.class);</div><div class="line"></div><div class="line"><span class="comment">// Use it (when configuration changes your object will be auto-updated!)</span></div><div class="line"><span class="keyword">if</span>(config.featureToggle()) &#123;</div><div class="line">    ...</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<h4 id="配置刷新"><a href="#配置刷新" class="headerlink" title="配置刷新"></a>配置刷新</h4><p>定时刷新配置：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line"><span class="comment">// Reload every second</span></div><div class="line">ConfigurationProvider provider = <span class="keyword">new</span> ConfigurationProviderBuilder()</div><div class="line">        .withConfigurationSource(...)</div><div class="line">        .withReloadStrategy(<span class="keyword">new</span> PeriodicalReloadStrategy(<span class="number">1</span>, TimeUnit.SECONDS))</div><div class="line">        .build();</div></pre></td></tr></table></figure>
<p>自定义触发刷新配置：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div></pre></td><td class="code"><pre><div class="line"><span class="comment">// Implement your strategy</span></div><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MyReloadStrategy</span> <span class="keyword">implements</span> <span class="title">ReloadStrategy</span> </span>&#123;</div><div class="line"></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">register</span><span class="params">(Reloadable resource)</span> </span>&#123;</div><div class="line">        ...</div><div class="line">        resource.reload();</div><div class="line">        ...</div><div class="line">    &#125;</div><div class="line"></div><div class="line">&#125;</div><div class="line"></div><div class="line">ConfigurationProvider provider = <span class="keyword">new</span> ConfigurationProviderBuilder()</div><div class="line">    .withReloadStrategy(<span class="keyword">new</span> MyReloadStrategy())</div><div class="line">    .build();</div></pre></td></tr></table></figure>
<h4 id="环境切换"><a href="#环境切换" class="headerlink" title="环境切换"></a>环境切换</h4><p>cfg4j使用Environment告诉配置服务配置文件的存储位置。通过Environment可以切换不同的环境获取各自对应的配置。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div></pre></td><td class="code"><pre><div class="line">ConfigurationProvider provider = <span class="keyword">new</span> ConfigurationProviderBuilder()</div><div class="line">    .withConfigurationSource(<span class="keyword">new</span> ConsulConfigurationSourceBuilder().build())</div><div class="line">    .withEnvironment(<span class="keyword">new</span> ImmutableEnvironment(<span class="string">"myApplication/prod"</span>)) <span class="comment">// each conf variable will be prefixed with this value when fetching from Consul</span></div><div class="line">    .build();</div></pre></td></tr></table></figure>
<h4 id="不同配置文件的支持"><a href="#不同配置文件的支持" class="headerlink" title="不同配置文件的支持"></a>不同配置文件的支持</h4><p>cfg4j使用ConfigurationSource读取配置文件的内容时，能够通过文件的扩展名(.properties 或.yaml)自动识别是Properties文件还是YAML文件。</p>
<h4 id="从多个配置源中合并配置"><a href="#从多个配置源中合并配置" class="headerlink" title="从多个配置源中合并配置"></a>从多个配置源中合并配置</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div></pre></td><td class="code"><pre><div class="line">ConfigurationSource source1 = ...</div><div class="line">ConfigurationSource source2 = ...</div><div class="line"></div><div class="line">ConfigurationSource mergedSource = <span class="keyword">new</span> MergeConfigurationSource(source1, source2);</div></pre></td></tr></table></figure>
<h4 id="故障情况下回退"><a href="#故障情况下回退" class="headerlink" title="故障情况下回退"></a>故障情况下回退</h4><p>在分布式环境中工作时，故障很难避免，因此，可以考虑使用多个来源，当一个失败时，另一个将被用作后备。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div></pre></td><td class="code"><pre><div class="line">ConfigurationSource source1 = ...</div><div class="line">ConfigurationSource source2 = ...</div><div class="line"></div><div class="line">ConfigurationSource mergedSource = <span class="keyword">new</span> FallbackConfigurationSource(source1, source2);</div></pre></td></tr></table></figure>
<p>更多详细示例请参考<a href="http://www.cfg4j.org/releases/latest/" target="_blank" rel="external">cfg4j官方文档</a>。</p>
<h3 id="快速开发"><a href="#快速开发" class="headerlink" title="快速开发"></a>快速开发</h3><p>在本地开发时，可以通过以下方式加快开发速度：</p>
<p>向项目中添加一个临时配置文件，并使用cfg4j的MergeConfigurationSource从配置存储和文件读取配置。通过将本地文件设置为主配置源，cfg4j可以使用覆盖机制，如果在文件中找到该属性，将使用它，否则，将回退到使用配置存储中的值。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div></pre></td><td class="code"><pre><div class="line"><span class="meta">@Bean</span></div><div class="line"><span class="function">ConfigurationProvider <span class="title">configurationProvider</span><span class="params">(ConfigurationSource configurationSource,</span></span></div><div class="line">@Value(<span class="string">"$&#123;configuration.environment&#125;"</span>) String configurationEnvironment) &#123;</div><div class="line"></div><div class="line">    ConfigurationSource localOverrideSource = <span class="keyword">new</span> FilesConfigurationSource(() -&gt; Collections.singletonList(Paths.get(<span class="string">"application.properties"</span>)));</div><div class="line">    MergeConfigurationSource mergeConfigurationSource = <span class="keyword">new</span> MergeConfigurationSource(localOverrideSource, configurationSource);</div><div class="line"></div><div class="line">    <span class="keyword">return</span> <span class="keyword">new</span> ConfigurationProviderBuilder()</div><div class="line">        .withConfigurationSource(mergeConfigurationSource)</div><div class="line">        .withEnvironment(<span class="keyword">new</span> ImmutableEnvironment(<span class="string">"app/"</span> + configurationEnvironment + <span class="string">"/feature"</span>))</div><div class="line">        .withReloadStrategy(<span class="keyword">new</span> PeriodicalReloadStrategy(<span class="number">30</span>, TimeUnit.SECONDS))</div><div class="line">        .build();</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>可以Fork一个配置库，对fork库的配置进行更改，并使用cfg4j的GitConfigurationSource直接访问它（不需要推送缓存）。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div></pre></td><td class="code"><pre><div class="line"><span class="meta">@Bean</span></div><div class="line"><span class="function">ConfigurationProvider <span class="title">configurationProvider</span><span class="params">(@Value(<span class="string">"$&#123;configuration.environment&#125;"</span>)</span> String configurationEnvironment) </span>&#123;</div><div class="line">    ConfigurationSource GitSource = <span class="keyword">new</span> GitConfigurationSourceBuilder()</div><div class="line">        .withRepositoryURI(<span class="string">"https://Github.com/myUser/my-config-fork.Git"</span>)</div><div class="line">        .build();</div><div class="line"></div><div class="line">    <span class="keyword">return</span> <span class="keyword">new</span> ConfigurationProviderBuilder()</div><div class="line">    .withConfigurationSource(GitSource)</div><div class="line">    .withEnvironment(<span class="keyword">new</span> ImmutableEnvironment(<span class="string">"app/"</span> + configurationEnvironment + <span class="string">"/feature"</span>))</div><div class="line">    .withReloadStrategy(<span class="keyword">new</span> PeriodicalReloadStrategy(<span class="number">30</span>, TimeUnit.SECONDS))</div><div class="line">    .build();</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>设置一个私有的推送缓存，将开发的服务指向该缓存，并直接在缓存修改配置。</p>
<h3 id="参考"><a href="#参考" class="headerlink" title="参考"></a>参考</h3><ul>
<li><p>关于微服务框架相关实践及与DC/OS的整合请参考:<a href="http://chrisrc.me/dcos">《DC/OS修炼之路》</a>。</p>
</li>
<li><p><a href="http://code.flickr.net/2016/03/24/configuration-management-for-distributed-systems-using-github-and-cfg4j/" target="_blank" rel="external">http://code.flickr.net/2016/03/24/configuration-management-for-distributed-systems-using-github-and-cfg4j/</a></p>
</li>
</ul>

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        

      
    </div>


    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/微服务/" rel="tag"># 微服务</a>
          
            <a href="/tags/microservice/" rel="tag"># microservice</a>
          
            <a href="/tags/Gitlab/" rel="tag"># Gitlab</a>
          
            <a href="/tags/配置管理/" rel="tag"># 配置管理</a>
          
            <a href="/tags/Cfg4j/" rel="tag"># Cfg4j</a>
          
            <a href="/tags/Consul/" rel="tag"># Consul</a>
          
            <a href="/tags/Jenkins/" rel="tag"># Jenkins</a>
          
            <a href="/tags/Vault/" rel="tag"># Vault</a>
          
        </div>
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2017/02/17/configuration-management-on-dcos-1/" rel="next" title="微服务之配置管理（1）—— 概述">
                <i class="fa fa-chevron-left"></i> 微服务之配置管理（1）—— 概述
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2017/02/19/configuration-management-on-dcos-vault/" rel="prev" title="微服务之配置管理（3）—— Vault的Secrets管理">
                微服务之配置管理（3）—— Vault的Secrets管理 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
        <div class="ds-share flat" data-thread-key="2017/02/18/configuration-management-on-dcos-cfg4j/"
     data-title="微服务之配置管理（2）—— Cfg4j"
     data-content=""
     data-url="http://chrisrc.me/2017/02/18/configuration-management-on-dcos-cfg4j/">
  <div class="ds-share-inline">
    <ul  class="ds-share-icons-16">

      <li data-toggle="ds-share-icons-more"><a class="ds-more" href="javascript:void(0);">分享到：</a></li>
      <li><a class="ds-weibo" href="javascript:void(0);" data-service="weibo">微博</a></li>
      <li><a class="ds-qzone" href="javascript:void(0);" data-service="qzone">QQ空间</a></li>
      <li><a class="ds-qqt" href="javascript:void(0);" data-service="qqt">腾讯微博</a></li>
      <li><a class="ds-wechat" href="javascript:void(0);" data-service="wechat">微信</a></li>

    </ul>
    <div class="ds-share-icons-more">
    </div>
  </div>
</div>
      
    </div>
  </div>


          </div>
          


          
  <div class="comments" id="comments">
    
      <div class="ds-thread" data-thread-key="2017/02/18/configuration-management-on-dcos-cfg4j/"
           data-title="微服务之配置管理（2）—— Cfg4j" data-url="http://chrisrc.me/2017/02/18/configuration-management-on-dcos-cfg4j/">
      </div>
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/images/avatar.gif"
               alt="chrisrc" />
          <p class="site-author-name" itemprop="name">chrisrc</p>
          <p class="site-description motion-element" itemprop="description"></p>
        </div>
        <nav class="site-state motion-element">
          <div class="site-state-item site-state-posts">
            <a href="/archives">
              <span class="site-state-item-count">69</span>
              <span class="site-state-item-name">日志</span>
            </a>
          </div>

          
            <div class="site-state-item site-state-categories">
              <a href="/categories">
                <span class="site-state-item-count">21</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            <div class="site-state-item site-state-tags">
              <a href="/tags">
                <span class="site-state-item-count">162</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        

        <div class="links-of-author motion-element">
          
            
              <span class="links-of-author-item">
                <a href="https://github.com/christtrc" target="_blank" title="GitHub">
                  
                    <i class="fa fa-fw fa-github"></i>
                  
                  GitHub
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://twitter.com/chrisrc" target="_blank" title="Twitter">
                  
                    <i class="fa fa-fw fa-twitter"></i>
                  
                  Twitter
                </a>
              </span>
            
          
        </div>

        
        
          <div class="cc-license motion-element" itemprop="license">
            <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" class="cc-opacity" target="_blank">
              <img src="/images/cc-by-nc-sa.svg" alt="Creative Commons" />
            </a>
          </div>
        

        
        

        


      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#功能示例"><span class="nav-number">1.</span> <span class="nav-text">功能示例</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#添加依赖"><span class="nav-number">1.1.</span> <span class="nav-text">添加依赖</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#初始化配置服务"><span class="nav-number">1.2.</span> <span class="nav-text">初始化配置服务</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#访问配置"><span class="nav-number">1.3.</span> <span class="nav-text">访问配置</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#配置刷新"><span class="nav-number">1.4.</span> <span class="nav-text">配置刷新</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#环境切换"><span class="nav-number">1.5.</span> <span class="nav-text">环境切换</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#不同配置文件的支持"><span class="nav-number">1.6.</span> <span class="nav-text">不同配置文件的支持</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#从多个配置源中合并配置"><span class="nav-number">1.7.</span> <span class="nav-text">从多个配置源中合并配置</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#故障情况下回退"><span class="nav-number">1.8.</span> <span class="nav-text">故障情况下回退</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#快速开发"><span class="nav-number">2.</span> <span class="nav-text">快速开发</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#参考"><span class="nav-number">3.</span> <span class="nav-text">参考</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy;  2015 - 
  <span itemprop="copyrightYear">2017</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">
     
      <a href="mailto:chrisrc@qq.com">chrisrc</a> 
    
  </span>
  <span class="author"> &nbsp; QQ: 58122705 </span>
</div>


<div class="powered-by">
  由 <a class="theme-link" href="https://hexo.io">Hexo</a> 强力驱动
</div>

<div class="theme-info">
  主题 -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Mist
  </a>
</div>


        

        
      </div>
    </footer>

    <div class="back-to-top">
      <i class="fa fa-arrow-up"></i>
    </div>
  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  



  
  <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.0"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.0"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.0"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.0"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.0"></script>



  

  
    
  

  <script type="text/javascript">
    var duoshuoQuery = {short_name:"chrisrc"};
    (function() {
      var ds = document.createElement('script');
      ds.type = 'text/javascript';ds.async = true;
      ds.id = 'duoshuo-script';
      ds.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') + '//static.duoshuo.com/embed.js';
      ds.charset = 'UTF-8';
      (document.getElementsByTagName('head')[0]
      || document.getElementsByTagName('body')[0]).appendChild(ds);
    })();
  </script>

  
    
    
    <script src="/lib/ua-parser-js/dist/ua-parser.min.js?v=0.7.9"></script>
    <script src="/js/src/hook-duoshuo.js"></script>
  








  
  

  

  

  
<script>
(function(){
    var bp = document.createElement('script');
    var curProtocol = window.location.protocol.split(':')[0];
    if (curProtocol === 'https') {
        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';        
    }
    else {
        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
    }
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(bp, s);
})();
</script>


  
<script>
(function(){
   var src = (document.location.protocol == "http:") ? "http://js.passport.qihucdn.com/11.0.1.js?ed903ab05fbc5fa64d95e4bfbf3d3a04":"https://jspassport.ssl.qhimg.com/11.0.1.js?ed903ab05fbc5fa64d95e4bfbf3d3a04";
   document.write('<script src="' + src + '" id="sozz"><\/script>');
})();
</script>

  


</body>
</html>
